import axios from 'axios'
import router from '../router'
import service from './contactApi'
import { Message ,MessageBox} from 'element-ui'
import { getToken, removeToken } from '@/utils/auth'
import utils from '@/utils/utils'
import { errorCode, successCode } from '@/service/httpCode'

// service 循环遍历输出不容的请求方法
const instance = axios.create({
    baseURL: utils.data.baseURL,
    timeout: 600000
})


const Http = {} // 请求方法的容器
let isLogin = true;
// 请求格式统一
for (const key in service) {
    const api = service[key]
        // async 作用：避免进入回调地狱
    Http[key] = async function( // 参数
        params, // 请求参数
        isFormData = false, // 是否是form-data请求
        config = {} // 请求配置参数
    ) {
        let newParams = {} // 为转换form-data格式
        api.config ? config = api.config : '';
        // content-type 是否试form-data的判断
        if (params && isFormData) {
            console.log(params, "paramsparams");
            newParams = new FormData()
            for (const i in params) {
                newParams.append(i, params[i])
            }
        } else {
            newParams = params
        }



        // 不同请求判断
        let response = {} // 请求返回值
        if (api.method === 'post' || api.method === 'put' || api.method === 'patch') {
            try {
                response = await instance[api.method](api.url, newParams, config)
            } catch (err) {
                response = err
            }
        } else if (api.method === 'get' || api.method === 'delete') {
            config.params = newParams
            try {
                response = await instance[api.method](api.url, config)
            } catch (err) {
                response = err
            }
        }
        return response // 返回响应值
    }
}

const axiosPromiseArr = []
    // 请求拦截器
instance.interceptors.request.use(
    config => {
        let token = getToken() || ''
        if (token) {
            config.headers['x-store-token'] = token; //将token放到请求头发送给服务器
        }
        config.cancelToken = new axios.CancelToken(cancel => {
                axiosPromiseArr.push({
                    cancel
                })
            })
            // // 请求等待lodding 遮罩层
            // store.commit('loaddingShow', true)
        return config
    }, () => {
        // 清除loadding
        // store.commit('loaddingShow', false)
        Message.error('请求错误')
    }
)

// 响应拦截器
instance.interceptors.response.use(
    res => {
        if (res.status !== 200) {
            Message.error(res.msg)
            return new Promise(() => {})
        } else {
            let resData = res.data
            if (!successCode[resData.code] && resData.code) {
                if (resData.code >= 11101 && resData.code <= 11110&&isLogin) {
                    console.log("重新登录");
                    isLogin = false;
                    MessageBox.confirm(`${errorCode[resData.code]},需要重新登录`, '提示', {
                        confirmButtonText: '重新登录',
                        type: 'warning'
                    }).then(() => {
                        removeToken();
                        router.push('/login');
                        isLogin = true;
                    }).catch(() => {
                        isLogin = true;
                    });
                }else if(resData.msg)
                    Message({
                    message: res.data.msg,
                    type: 'error',
                    duration: 5 * 1000
                    })
                // console.log(resData);  Promise.reject(new Error(resData.msg || 'Error'))
                resData.code = false;
                return resData
            } else {
                return resData
            }

        }
        // 清除loadding
        // store.commit('loaddingShow', false)
        // if (res.data.code && res.data.code != 200) {
        //     if (res.data.code == -1 || res.data.code == -40000) {
        //         removeToken()
        //         Message.error('请重新登录')
        //         router.push('/login')
        //     } else {
        //         console.log(res)
        //         Message.error(res.data.message)
        //     }
        // }
    }, (error) => {
        console.log("🤬 ~ Httperror", error.response)
            // 清除loadding
            // store.commit('loaddingShow', false)
            // 取消请求的情况下，终端Promise调用链（判断是取消还是响应错误）
        if (axios.isCancel(error)) {
            console.log('取消请求成功')
            return new Promise(() => {})
        } else {
            Message({
                message:error?.response?.data?.message?"请求错误:"+ error.response.data.message:'请求错误',
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(error)
        }
    }
)

export default {
    Http,
    axiosPromiseArr
}